package com.recharge.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.recharge.common.domain.PageDO;
import com.recharge.common.enums.ErrorCode;
import com.recharge.common.result.ResultDO;
import com.recharge.common.result.ResultSupport;
import com.recharge.common.util.BeanUtilsExtends;
import com.recharge.common.util.http.MapTool;
import com.recharge.core.entity.RoleDataPermissionEntity;
import com.recharge.core.mapper.RoleDataPermissionMapper;
import com.recharge.domain.query.RoleDataPermissionQueryDO;
import com.recharge.domain.vo.RoleDataPermissionDO;
import com.recharge.service.RoleDataPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import java.util.stream.Collectors;

@Service
public class RoleDataPermissionServiceImpl extends ServiceImpl<RoleDataPermissionMapper,RoleDataPermissionEntity> implements RoleDataPermissionService {

    private Logger logger = Logger.getLogger(this.getClass().getName());

    @Autowired
    private RoleDataPermissionMapper roleDataPermissionMapper;


    @Transactional(propagation= Propagation.REQUIRED, rollbackFor= Exception.class)
    public ResultDO edit(RoleDataPermissionDO domain) {

        RoleDataPermissionEntity entity = new RoleDataPermissionEntity();
        ResultDO result = BeanUtilsExtends.copy(entity, domain);
        if (!result.isSuccess()) {
            logger.info("error code：" + result.getErrorCode().getCode() + " msg" + result.getErrorCode().getMsg());
            return result;
        }

        QueryWrapper<RoleDataPermissionEntity> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(RoleDataPermissionEntity::getRoleId,domain.getRoleId());
        wrapper.lambda().eq(RoleDataPermissionEntity::getTableName,domain.getTableName());


        try {
            baseMapper.delete(wrapper);
        }catch (Exception e){
            e.printStackTrace();
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.info("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        try {
            List<RoleDataPermissionEntity> entityList = new ArrayList<>();

            for (Map<String,String> s : domain.getFields()) {
                RoleDataPermissionEntity tempEntity = new RoleDataPermissionEntity();
                tempEntity.setRoleId(entity.getRoleId());
                tempEntity.setTableName(entity.getTableName());
                tempEntity.setTableField(s.get("tableField"));
                tempEntity.setTableFieldComment(s.get("tableFieldComment"));
                tempEntity.setSqlType(1);
                entityList.add(tempEntity);

                //baseMapper.insert(entity);
            }
            this.saveBatch(entityList);
        }catch (Exception e){
            e.printStackTrace();
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.info("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        return result;
    }

    @Transactional(propagation= Propagation.REQUIRED, rollbackFor= Exception.class)
    public List<Map<String,Object>> getPermissionField(RoleDataPermissionQueryDO queryDO) {
        ResultDO result = new ResultSupport();
        Map<String,Object> param = new HashMap<>();
        param.put("tableName",queryDO.getTableName());
        if(queryDO.getRoleId()!=null&&!queryDO.getRoleId().equals("")){
            param.put("roleIds",queryDO.getRoleId().split(","));
        }else if(queryDO.getRoleIds()!=null && queryDO.getRoleIds().length>0){
            param.put("roleIds",queryDO.getRoleIds());
        }

        List<Map<String,Object>> map = null;
        try {
            map = roleDataPermissionMapper.getFieldListByRole(param);
        }catch (Exception e){
            e.printStackTrace();
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.info("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return null;
        }
        return map;
    }

    @Transactional(propagation= Propagation.REQUIRED, rollbackFor= Exception.class)
    public ResultDO findField(RoleDataPermissionQueryDO queryDO) {
        ResultDO result = new ResultSupport();
        Map<String,Object> param = new HashMap<>();
        param.put("tableName",queryDO.getTableName());

        List<Map<String,Object>> map = null;
        try {
           map = roleDataPermissionMapper.getFieldList(param);
        }catch (Exception e){
            e.printStackTrace();
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.info("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        List<RoleDataPermissionDO> list = null;
        list = map.stream().map(m->{
            RoleDataPermissionDO roleDataPermissionDO = MapTool.map2Bean(m,RoleDataPermissionDO.class,true);
            return roleDataPermissionDO;
        }).collect(Collectors.toList());

        if(queryDO.getRoleId()!=null&&!queryDO.getRoleId().equals("")){
            param.put("roleIds",queryDO.getRoleId().split(","));
        }else if(queryDO.getRoleIds()!=null && queryDO.getRoleIds().length>0){
            param.put("roleIds",queryDO.getRoleIds());
        }
        try {
            map = roleDataPermissionMapper.getFieldListByRole(param);
        }catch (Exception e){
            e.printStackTrace();
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.info("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return null;
        }
//        List<RoleDataPermissionDO> permissionlist = null;
//        permissionlist = map.stream().map(m->{
//            RoleDataPermissionDO roleDataPermissionDO = MapTool.map2Bean(m,RoleDataPermissionDO.class,true);
//            return roleDataPermissionDO;
//        }).collect(Collectors.toList());
        for(Map<String,Object> permissionDO:map){
            boolean bo = false;
            for(int i=0;i<list.size();i++){
                if(list.get(i).getTableField().equals(permissionDO.get("tableField"))){
                    RoleDataPermissionDO permissionDO1 = list.get(i);
                    permissionDO1.setChecked(true);
                    list.set(i,permissionDO1);
                    bo=true;
                    break;
                }
            }
            if(!bo){
                RoleDataPermissionDO adddo = new RoleDataPermissionDO();
                adddo.setTableField(permissionDO.get("tableField").toString());
                adddo.setTableName(permissionDO.get("tableName").toString());
                adddo.setChecked(true);
                list.add(adddo);
            }
        }

        PageDO<RoleDataPermissionDO> pageDO = new PageDO<>();
        pageDO.setData(list);
        result.setModel(ResultDO.FIRST_MODEL_KEY, pageDO);

        return result;
    }

    @Transactional(propagation= Propagation.REQUIRED, rollbackFor= Exception.class)
    public ResultDO findTable() {
        ResultDO result = new ResultSupport();
        List<Map<String,Object>> map = null;
        try {
            map = roleDataPermissionMapper.getAllTable();
        }catch (Exception e){
            e.printStackTrace();
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.SYSTEM_EXCEPTION);
            logger.info("error code：" + ErrorCode.SYSTEM_EXCEPTION.getCode() + " msg" + ErrorCode.SYSTEM_EXCEPTION.getMsg());
            return result;
        }

        List<RoleDataPermissionDO> list = null;
        list = map.stream().map(m->{
            RoleDataPermissionDO roleDataPermissionDO =MapTool.map2Bean(m,RoleDataPermissionDO.class,true);
            return roleDataPermissionDO;
        }).collect(Collectors.toList());

        PageDO<RoleDataPermissionDO> pageDO = new PageDO<>();
        pageDO.setData(list);
        result.setModel(ResultDO.FIRST_MODEL_KEY, pageDO);

        return result;
    }

}
